package leetcode;

import java.util.Arrays;

/**
 * @author:xufengxiang
 * @date 2023-03-09 20:00
 */
public class Code16 {

    public static int threeSumClosest(int[] nums, int target) {

        int length = nums.length;
        Arrays.sort(nums);
        int closest = nums[0] + nums[1] + nums[2];

        for(int i=0; i<length-2 ;i++){
            int left = i+1;
            int right = length-1;

            while(left < right){
                int cur = nums[i] + nums[left] + nums[right];
                if(Math.abs(cur-target) < Math.abs(closest - target)){
                    closest = cur;
                }
                if(cur < target){
                    left ++;
                } else if(cur > target){
                    right--;
                }else{
                    return target;
                }
            }
        }
        return closest;
    }

    public static void main(String[] args) {
        int i = threeSumClosest(new int[]{-1, 2, 1, -4}, 1);
        System.out.println(i);
    }



}
